<?php
	require_once '../../core/Debug.php'; //System Debug...
	require_once '../../core/config.php';//System Config...
	require_once '../../core/Init.php';  //System Init...

	if(User::have_permit(ADMIN_ITEM) && (int)Url::get('user_id',0) && (int)Url::get('user_id',0)!=User::id())
	{
		$user_id	=(int)Url::get('user_id',0);
		$user_name	='';
		$user		=User::getUser($user_id);
		if($user)
		$user_name	=$user['user_name'];
	}
	else{
		$user_id	=User::id();
		$user_name	=User::user_name();
	}
		
	$json['error'] 		= 'not_uploaded';
	$json['id'] 		= 0;
	$json['image_url']	= '';
	
	if(User::is_login()){
		if(User::is_az_team() || User::level()>0){
			$upload_path= AZLib::folderUpload($user_id);
			
			if(AZLib::ftp_check_dir($upload_path,true,IMAGE_SERVER_NO)){//Check dir for upload
				$uploadFile = $_FILES["fast_upload_avatar"];
				if(isset($uploadFile) && $uploadFile['name']){
					$file_name	=$uploadFile['name'];
					$sourceName 	= $uploadFile['tmp_name'];
					$file_ext	=AZLib::getExtension($file_name);
					
					if(in_array($file_ext,array('.jpg','.jpeg','.gif','.png'))){	
						if(!$uploadFile['error'])
						{
							list($imagewidth, $imageheight, $imageType) = getimagesize($uploadFile['tmp_name']);
							if($imagewidth && $uploadFile['size']<=Item::MAX_UPLOAD_SIZE ){

								$img_url   = $upload_path.date("YmdHis",TIME_NOW) . '_'.substr(AZLib::make_safe_name(basename(strtolower($file_name),$file_ext)),0,36).$file_ext;	
						
								if(AZLib::ftp_image_put_file($img_url,$sourceName,IMAGE_SERVER_NO)){
									$image_id = DB::insert('item_image',array(
																			  'des'					=>'',
																			  'item_id'				=>0,
																			  'title'				=>'',
																			  'position'			=>0,
																			   'img_server'	=>IMAGE_SERVER_NO,
																			  'img_url'	=>$img_url,
																			  'root_id'				=>0,
																			  'time'				=>TIME_NOW,
																			  'user_id'				=>$user_id,
																			  'user_name'			=>$user_name
																			  ));
									if($image_id){
										$json['id'] 		= $image_id;
										$json['img_server'] 	= IMAGE_SERVER_NO;
										$json['image_url']	= $img_url;
										
										$json['error'] 		= 'success';
									}
								}
							}
							else{
								$json['error'] = 'over_max_size';//Sai định dạng file hoặc upload dung lượng quá lớn
							}
						}
						elseif($uploadFile['error'] == 1)
						{
							$json['error'] = 'over_max_size';
						}
					}
					else{
						$json['error'] = 'ext_invalid';//Sai định dạng file
					}
				}
				else
				{
					$json['error'] = 'source_file_error';
				}
			}
			else
			{
				$json['error'] = 'destination_not_exist';
			}
		}
		else
		{
			$json['error'] = 'not_have_permission';
		}
	}
	else{
		$json['error'] = 'not_login';
	}
	
	echo json_encode($json);
	exit();
?>